import { createRouter, createWebHistory } from 'vue-router'
import index from '../views/index.vue'
import { useBreadStore } from '@/stores/breadCrumbs'
import { cateLabel } from '@/utils/tool'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: index,
      meta: {
        title: '首页'
      }
    },
    {
      path: '/class',
      name: 'class',
      component: () => import('../views/class.vue'),
      meta: {
        title: '全部商品'
      }
    },
    {
      path: '/goods',
      name: 'goods',
      component: () => import('../views/goods.vue'),
      meta: {
        title: '商品详情'
      }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login.vue'),
      meta: {
        title: '登陆'
      }
    },
    {
      path: '/order',
      name: 'order',
      component: () => import('../views/order.vue'),
      meta: {
        title: '订单'
      }
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/about.vue'),
      meta: {
        title: '关于我们'
      }
    },
    {
      path: '/mine',
      component: () => import('../views/mine.vue'),
      meta: {
        title: '我的'
      },
      redirect: 'personal',
      children: [
        {
          path: 'personal',
          component: () => import('../views/personal.vue'),
          name: 'personal',
          meta: {
            title: '个人信息'
          }
        },
        {
          path: 'myorder',
          component: () => import('../views/myOrder.vue'),
          name: 'myorder',
          meta: {
            title: '我的账单'
          }
        }
      ]
    }
  ]
})
router.beforeEach((to, from, next) => {
  let { router_list } = useBreadStore() as any
  if (to.path == '/class' && to.query.id) {
    to.meta.title = cateLabel(to.query.id as string)
  }
  if (router_list.some((item: any) => item.path === to.path)) {
    const index = router_list.findIndex((item: any) => item.path === to.path)
    let temp = router_list.slice(0, index)
    temp.push(to)
    router_list.splice(0, router_list.length)
    router_list.push(...temp)
  } else {
    router_list.push(to)
  }
  document.title = to.meta.title as string
  next()
})
export default router
